<template>
  <div class="startup-container">
    <h2 class="startup-title">一键启动</h2>
    <div class="service-list">
      <div v-for="service in services" :key="service.id" class="service-item">
        <div class="service-info">
          <h3>{{ service.name }}</h3>
          <p>{{ service.description }}</p>
        </div>
        <div class="service-actions">
          <el-button
            :type="service.running ? 'danger' : 'primary'"
            :loading="service.loading"
            @click="toggleService(service.id)"
          >
            {{ service.running ? '停止' : '启动' }}
          </el-button>
          <span class="service-status">{{ service.status }}</span>
        </div>
      </div>
    </div>

    <div class="operation-area">
      <el-button
        type="primary"
        size="large"
        :loading="globalLoading"
        @click="startAllServices"
        :disabled="allRunning"
      >
        启动全部服务
      </el-button>
      <el-button
        type="danger"
        size="large"
        :loading="globalLoading"
        @click="stopAllServices"
        :disabled="allStopped"
      >
        停止全部服务
      </el-button>
    </div>

    <div class="log-area" v-if="showLogs">
      <h3>运行日志</h3>
      <div class="log-content">
        <p v-for="log in logs" :key="log.id">{{ log.timestamp }}: {{ log.message }}</p>
      </div>
    </div>
  </div>
</template>

<script setup>
import { ref, computed } from 'vue'
import { ElMessage, ElButton } from 'element-plus'
import {
  wcao,
  post
} from "@/http";

// 服务列表数据
const services = ref([
  { id: 1, name: '前端开发服务器', description: '启动本地开发服务器', running: false, loading: false, status: '未启动' },
  { id: 2, name: '后端API服务', description: '启动后端API服务', running: false, loading: false, status: '未启动' },
  { id: 3, name: '数据库服务', description: '启动数据库服务', running: false, loading: false, status: '未启动' },
  { id: 4, name: '文件服务', description: '启动文件存储服务', running: false, loading: false, status: '未启动' }
])

const logs = ref([])
const globalLoading = ref(false)
const showLogs = ref(true)

// 计算属性
const allRunning = computed(() => services.value.every(service => service.running))
const allStopped = computed(() => services.value.every(service => !service.running))

// 切换单个服务状态
function toggleService(id) {
  const service = services.value.find(s => s.id === id)
  if (!service) return

  service.loading = true
  const action = service.running ? 'stop' : 'start'

  http.post(`/api/service/${action}`, { serviceId: id })
    .then(response => {
      if (response.data.success) {
        service.running = !service.running
        service.status = service.running ? '运行中' : '已停止'
        addLog(`${service.name} ${service.running ? '启动' : '停止'}成功`)
        ElMessage.success(`${service.name} ${service.running ? '启动' : '停止'}成功`)
      } else {
        ElMessage.error(`${service.name} ${action === 'start' ? '启动' : '停止'}失败: ${response.data.message}`)
        addLog(`${service.name} ${action === 'start' ? '启动' : '停止'}失败: ${response.data.message}`)
      }
    })
    .catch(error => {
      ElMessage.error(`${service.name} ${action === 'start' ? '启动' : '停止'}出错: ${error.message}`)
      addLog(`${service.name} ${action === 'start' ? '启动' : '停止'}出错: ${error.message}`)
    })
    .finally(() => {
      service.loading = false
    })
}

// 启动所有服务
function startAllServices() {
  if (allRunning.value) {
    ElMessage.info('所有服务已处于运行状态')
    return
  }

  globalLoading.value = true
  addLog('开始启动所有服务...')

  Promise.all(
    services.value
      .filter(service => !service.running)
      .map(service => {
        service.loading = true
        return http.post('/api/service/start', { serviceId: service.id })
          .then(response => {
            if (response.data.success) {
              service.running = true
              service.status = '运行中'
              addLog(`${service.name} 启动成功`)
            } else {
              addLog(`${service.name} 启动失败: ${response.data.message}`)
            }
            return response
          })
          .catch(error => {
            addLog(`${service.name} 启动出错: ${error.message}`)
            return { data: { success: false } }
          })
          .finally(() => {
            service.loading = false
          })
      })
  )
    .then(results => {
      const allSuccess = results.every(res => res.data.success)
      if (allSuccess) {
        ElMessage.success('所有服务启动成功')
      } else {
        ElMessage.warning('部分服务启动失败，请查看日志')
      }
      addLog('所有服务启动操作完成')
    })
    .finally(() => {
      globalLoading.value = false
    })
}

// 停止所有服务
function stopAllServices() {
  if (allStopped.value) {
    ElMessage.info('所有服务已处于停止状态')
    return
  }

  globalLoading.value = true
  addLog('开始停止所有服务...')

  Promise.all(
    services.value
      .filter(service => service.running)
      .map(service => {
        service.loading = true
        return http.post('/api/service/stop', { serviceId: service.id })
          .then(response => {
            if (response.data.success) {
              service.running = false
              service.status = '已停止'
              addLog(`${service.name} 停止成功`)
            } else {
              addLog(`${service.name} 停止失败: ${response.data.message}`)
            }
            return response
          })
          .catch(error => {
            addLog(`${service.name} 停止出错: ${error.message}`)
            return { data: { success: false } }
          })
          .finally(() => {
            service.loading = false
          })
      })
  )
    .then(results => {
      const allSuccess = results.every(res => res.data.success)
      if (allSuccess) {
        ElMessage.success('所有服务停止成功')
      } else {
        ElMessage.warning('部分服务停止失败，请查看日志')
      }
      addLog('所有服务停止操作完成')
    })
    .finally(() => {
      globalLoading.value = false
    })
}

// 添加日志
function addLog(message) {
  const timestamp = new Date().toLocaleTimeString()
  logs.value.push({ id: Date.now(), timestamp, message })
  // 保持日志最多显示100条
  if (logs.value.length > 100) {
    logs.value.shift()
  }
}
</script>

<style scoped>
.startup-container {
  max-width: 900px;
  margin: 0 auto;
  padding: 32px;
}

.startup-title {
  text-align: center;
  font-size: 24px;
  font-weight: bold;
  margin-bottom: 24px;
}

.service-list {
  margin-bottom: 32px;
}

.service-item {
  display: flex;
  justify-content: space-between;
  align-items: center;
  padding: 16px;
  border-bottom: 1px solid #eee;
  background-color: #f9f9f9;
  border-radius: 8px;
  margin-bottom: 12px;
}

.service-info h3 {
  margin: 0 0 8px 0;
  font-size: 18px;
}

.service-info p {
  margin: 0;
  color: #666;
  font-size: 14px;
}

.service-actions {
  display: flex;
  align-items: center;
  gap: 12px;
}

.service-status {
  padding: 4px 8px;
  border-radius: 4px;
  font-size: 12px;
}

.operation-area {
  display: flex;
  justify-content: center;
  gap: 16px;
  margin-bottom: 32px;
}

.log-area {
  background-color: #f0f0f0;
  border-radius: 8px;
  padding: 16px;
  max-height: 300px;
  overflow-y: auto;
}

.log-content {
  font-family: monospace;
  font-size: 14px;
  line-height: 1.5;
}

.log-content p {
  margin: 4px 0;
  border-bottom: 1px solid #eee;
  padding-bottom: 4px;
}
</style>